package io.litchi.auth.Infrastructure.handler;

import io.litchi.auth.Infrastructure.config.AuthConfig;
import io.litchi.auth.Infrastructure.securityentity.LitchiUser;
import io.litchi.auth.Infrastructure.util.ResponseUtil;
import io.litchi.auth.application.service.AuthService;
import io.litchi.auth.domain.entity.auth.User;
import io.litchi.common.result.Result;
import io.litchi.starter.jjwt.JwtManager;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Objects;

/**
 * description: 登录成功处理器
 *
 * @author helang
 * @since 2025-09-10
 */
@AllArgsConstructor
public class LitchiLoginSuccessHandler implements AuthenticationSuccessHandler {

    private JwtManager jwtManager;

    private AuthConfig authConfig;

    private AuthService authService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        //返回成功信息 token需在登录处理中生成
        // 1. 获取 UserDetails 或自定义用户对象
        LitchiUser userDetails = (LitchiUser) authentication.getPrincipal();
        User user = authService.findByUsername(userDetails.getUsername(), User.class).orElse(new User());

        // 2.生成token
        HashMap<String, Object> extData = new HashMap<>(16);
        extData.put("phone", user.getMobile());
        extData.put("lastLoginDate", Objects.nonNull(user.getLastLoginDate()) ?
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
                .format(user.getLastLoginDate()) : "");
        String token = jwtManager.createToken(userDetails.getUsername(), extData, authConfig.getExpireTime());
        String refreshToken = jwtManager.createToken(userDetails.getUsername(), extData, authConfig.getRefreshTime());
        userDetails.setId(user.getId());
        userDetails.setToken(token);
        userDetails.setRefreshToken(refreshToken);
        userDetails.setExpirationTime(authConfig.getExpireTime());
        userDetails.setRefreshTime(authConfig.getRefreshTime());
        userDetails.setExtUserInfo(extData);

        //修改登录时间
        authService.updateLastLoginDateById(user.getId());
        // 3.构建Result
        Result<LitchiUser> userResult = Result.success(userDetails);
        // 3.写回数据
        ResponseUtil.writeJsonResponse(response, userResult);
    }
}